<!DOCTYPE html>
<html>

<head>
    <title>box test World Population Visualization</title>
    <script type="text/javascript" src="https://unpkg.com/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@maptalks/gl/dist/maptalksgl.js"></script>
    <script type="text/javascript" src="https://unpkg.com/three@0.138.0/build/three.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/maptalks.three@latest/dist/maptalks.three.js"></script>
    <script type="text/javascript" src="https://unpkg.com/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/three@0.138.0/examples/js/libs/stats.min.js"></script>
    <style>
        html,
        body {
            margin: 0px;
            height: 100%;
            width: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>

        var map = new maptalks.Map("map", {
            center: [19.06325670775459, 42.16842479475318],
            zoom: 3,
            pitch: 60,
            // bearing: 180,

            centerCross: true,
            doubleClickZoom: false,
            baseLayer: new maptalks.TileLayer('tile', {
                urlTemplate: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c', 'd'],
                attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
            })
        });

        // the ThreeLayer to draw buildings
        var threeLayer = new maptalks.ThreeLayer('t', {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true
            // animation: true
        });
        threeLayer.prepareToDraw = function (gl, scene, camera) {
            stats = new Stats();
            stats.domElement.style.zIndex = 100;
            document.getElementById('map').appendChild(stats.domElement);

            var light = new THREE.DirectionalLight(0xffffff);
            light.position.set(0, -10, 10).normalize();
            scene.add(light);
            scene.add(new THREE.AmbientLight(0xffffff, 0.5));
            setTimeout(() => {
                addBars(scene);
            }, 1000);

        };
        const sceneConfig = {
            postProcess: {
                enable: true,
                antialias: { enable: true }
            }
        };
        const groupLayer = new maptalks.GroupGLLayer('group', [threeLayer], { sceneConfig });
        groupLayer.addTo(map);


        var bars;
        var material = new THREE.MeshLambertMaterial({ color: '#4491b1', transparent: true });
        var highlightmaterial = new THREE.MeshBasicMaterial({ color: 'yellow', transparent: true });
        function addBars(scene) {
            fetch('./data/population.json').then((function (res) {
                return res.json();
            })).then(function (json) {
                const time = 'time';
                console.time(time);
                bars = json.filter(function (dataItem) {
                    return dataItem[2] > 300;
                }).slice(0, Infinity).map(function (dataItem) {
                    return {
                        coordinate: dataItem.slice(0, 2),
                        height: dataItem[2]
                    }
                }).map(function (d) {
                    var bar = threeLayer.toBox(d.coordinate, {
                        height: d.height * 200,
                        radius: 15000,
                        topColor: '#fff',
                        // radialSegments: 4
                    }, material);

                    // // tooltip test
                    // bar.setToolTip(d.height * 400, {
                    //     showTimeout: 0,
                    //     eventsPropagation: true,
                    //     dx: 10
                    // });


                    // //infowindow test
                    // bar.setInfoWindow({
                    //     content: 'hello world,height:' + d.height * 400,
                    //     title: 'message',
                    //     animationDuration: 0,
                    //     autoOpenOn: false
                    // });


                    //event test
                    ['click', 'mouseout', 'mouseover', 'mousedown', 'mouseup', 'dblclick', 'contextmenu'].forEach(function (eventType) {
                        bar.on(eventType, function (e) {
                            // console.log(e.type, e);
                            // console.log(this);
                            if (e.type === 'mouseout') {
                                this.setSymbol(material);
                            }
                            if (e.type === 'mouseover') {
                                this.setSymbol(highlightmaterial);
                            }
                        });
                    });

                    return bar;
                });

                console.log(bars);
                console.timeEnd(time);

                threeLayer.addMesh(bars);
                initGui();
                animation();
            })
        }

        function animation() {
            // layer animation support Skipping frames
            threeLayer._needsUpdate = !threeLayer._needsUpdate;
            if (threeLayer._needsUpdate && !map.isInteracting()) {
                threeLayer.redraw();
            }
            stats.update();
            requestAnimationFrame(animation);
        }

        function initGui() {
            var params = {
                add: true,
                color: '#fff',
                show: true,
                opacity: 1,
                altitude: 0,
                animateShow: animateShow
            };

            var gui = new dat.GUI();
            gui.add(params, 'add').onChange(function () {
                if (params.add) {
                    threeLayer.addMesh(bars);
                } else {
                    threeLayer.removeMesh(bars);
                }
            });
            gui.addColor(params, 'color').name('bar color').onChange(function () {
                material.color.set(params.color);
                bars.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'opacity', 0, 1).onChange(function () {
                material.opacity = params.opacity;
                bars.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'show').onChange(function () {
                bars.forEach(function (mesh) {
                    if (params.show) {
                        mesh.show();
                    } else {
                        mesh.hide();
                    }
                });
            });
            gui.add(params, 'altitude', 0, 300000).onChange(function () {
                bars.forEach(function (mesh) {
                    mesh.setAltitude(params.altitude);
                });
            });
            gui.add(params, 'animateShow');
        }

        function animateShow() {
            bars.forEach(function (mesh) {
                mesh.animateShow({
                    duration: 3000
                });
            });
        }

    </script>
</body>

</html>